/**
 * @file kbd.c
 * @brief Keyboard Interface
 *
 * @version Fixed
 * @author yemit
 * @date 2010-06-17
 */
#include <sys/ioctl.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include "config.h"
#include "device.h"
#include "key.h"
#include "pm.h"

int key_fd;

pm_process_t powerkey_process = NULL;


void powerkey_register(void*func)
{
    powerkey_process = (pm_process_t)func;
}

void key_dev_init(void)
{
    key_fd = open(CONFIG_KBD_DEV, O_RDONLY|O_NONBLOCK);
}

int kb_get_key(int ms)
{
        fd_set readfds;
        struct timeval tv, * ptv;
        int ret;

        if (ms <= 0) ptv = NULL;
        else {
                tv.tv_sec = ms /1000;
                tv.tv_usec = (ms %1000) * 1000;
                ptv = &tv;
        }
        FD_ZERO(&readfds);
        FD_SET(key_fd, &readfds);
        ret = select(key_fd + 1, &readfds, NULL, NULL, ptv);
        if (ret <= 0) return ret;
        if (read(key_fd, &ret, 1) != 1) return -1;
#ifdef CONFIG_POWER_CTL
        if (ret == KEY_POWER) {
            if (powerkey_process) {
                sys_lcd_push();
                powerkey_process();
                sys_lcd_pop();
            }
            return 0;
        }
#endif
        return ret;
}

int press_key(void)
{
        fd_set readfds;
        struct timeval tv;
        int ret;

        tv.tv_sec = 0;
        tv.tv_usec = 100000;

        FD_ZERO(&readfds);
        FD_SET(key_fd, &readfds);
        ret = select(key_fd + 1, &readfds, NULL, NULL, &tv);
        if (ret <= 0) return ret;
        if (read(key_fd, &ret, 1) != 1) return -1;
        return ret;
}

void key_beep(uint32_t onoff)
{
        ioctl(key_fd, IOCTL_KEY_BEEP_ONOFF, (void *)onoff);
}
